<template>
  <div class="course-management-page">
    <div class="page-header">
      <h2 class="page-title">课程管理</h2>
      <div class="action-buttons">
        <el-button type="primary" @click="openAddCourseDialog">
          <i class="el-icon-plus"></i> 新增课程
        </el-button>
      </div>
    </div>

    <div class="course-list-container">
      <el-table
          :data="courseList"
          stripe
          border
          @selection-change="handleSelectionChange"
          class="course-table">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="courseID" label="课程ID" width="100"></el-table-column>
        <el-table-column label="课程封面" width="120">
          <template #default="scope">
            <img :src="scope.row.img" alt="课程封面" class="course-image">
          </template>
        </el-table-column>
        <el-table-column prop="name" label="课程名称"></el-table-column>
        <el-table-column prop="price" label="价格" width="100">
          <template #default="scope">
            {{ scope.row.price === 0 ? '免费' : `¥${scope.row.price}` }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button
                size="small"
                @click="openEditCourseDialog(scope.row)">
              编辑
            </el-button>
            <el-button
                size="small"
                type="danger"
                @click="handleDeleteCourse(scope.row.courseID)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
      </div>
    </div>

    <!-- 新增/编辑课程对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="600px"
        @open="onDialogOpen"
        @close="onDialogClose"
        :append-to-body="true">

      <template #default>
        <el-form :model="formData" :rules="formRules" ref="formRef" label-width="120px">
          <el-form-item label="课程名称" prop="name">
            <el-input v-model="formData.name"></el-input>
          </el-form-item>
          <el-form-item label="课程描述" prop="desc">
            <el-input type="textarea" v-model="formData.desc" :rows="4"></el-input>
          </el-form-item>
          <el-form-item label="课程价格" prop="price">
            <el-input-number v-model="formData.price" min="0"></el-input-number>
          </el-form-item>
          <el-form-item label="课程封面" prop="img">
            <el-upload
                class="avatar-uploader"
                :action="uploadUrl"
                :show-file-list="false"
                :on-success="handleUploadSuccess"
                :before-upload="beforeUpload"
                :headers="uploadHeaders">
              <img v-if="formData.img" :src="formData.img" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-form>
      </template>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="validateAndSave">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, nextTick } from 'vue';
import { ElTable, ElTableColumn, ElPagination, ElButton, ElDialog, ElForm, ElFormItem, ElInput, ElInputNumber, ElUpload, ElMessageBox, ElMessage } from 'element-plus';
import { getCourseList, addCourse, updateCourse, deleteCourse } from '@/api/course.js';

export default {
  components: {
    ElTable,
    ElTableColumn,
    ElPagination,
    ElButton,
    ElDialog,
    ElForm,
    ElFormItem,
    ElInput,
    ElInputNumber,
    ElUpload,
    ElMessageBox,
    ElMessage
  },
  setup() {
    const courseList = ref([]);
    const currentPage = ref(1);
    const pageSize = ref(10);
    const total = ref(0);
    const multipleSelection = ref([]);
    const dialogVisible = ref(false);
    const formData = ref({
      courseID: null,
      name: '',
      desc: '',
      price: 0,
      img: ''
    });
    const dialogTitle = ref('新增课程');
    const isEditMode = ref(false);
    const formRef = ref(null);
    const uploadUrl = ref('https://jsonplaceholder.typicode.com/posts/');
    const uploadHeaders = ref({});

    // 表单验证规则
    const formRules = {
      name: [
        { required: true, message: '请输入课程名称', trigger: 'blur' }
      ],
      price: [
        { required: true, message: '请输入课程价格', trigger: 'blur' },
        { type: 'number', message: '价格必须为数字值', trigger: 'blur' }
      ]
    };

    // 获取课程列表
    const fetchCourseList = async () => {
      try {
        const res = await getCourseList({
          page: currentPage.value,
          pageSize: pageSize.value
        });

        if (res.code === 1) {
          courseList.value = res.data.items;
          total.value = res.data.total;
        } else {
          console.error('获取课程列表失败：', res.message);
          ElMessage.error(res.message || '获取课程列表失败');
        }
      } catch (error) {
        console.error('请求课程列表出错：', error);
        ElMessage.error('网络错误，请稍后重试');
      }
    };

    // 打开新增课程对话框
    const openAddCourseDialog = () => {
      console.log('尝试打开新增课程对话框');

      dialogTitle.value = '新增课程';
      isEditMode.value = false;
      formData.value = {
        name: '',
        desc: '',
        price: 0,
        img: ''
      };

      nextTick(() => {
        if (formRef.value) {
          formRef.value.resetFields();
        }
      });

      dialogVisible.value = true;
      console.log('对话框状态：', dialogVisible.value);

      // 检查DOM中是否存在对话框元素
      nextTick(() => {
        const dialogElement = document.querySelector('.el-dialog');
        if (dialogElement) {
          console.log('对话框元素存在于DOM中');
          console.log('对话框样式：', window.getComputedStyle(dialogElement));
        } else {
          console.log('对话框元素不存在于DOM中');
        }
      });
    };

    // 打开编辑课程对话框
    const openEditCourseDialog = (course) => {
      console.log('尝试打开编辑课程对话框', course);

      dialogTitle.value = '编辑课程';
      isEditMode.value = true;
      formData.value = {
        courseID: course.courseID,
        name: course.name,
        desc: course.desc,
        price: course.price,
        img: course.img
      };

      nextTick(() => {
        if (formRef.value) {
          formRef.value.resetFields();
        }
      });

      dialogVisible.value = true;
      console.log('对话框状态：', dialogVisible.value);

      // 检查DOM中是否存在对话框元素
      nextTick(() => {
        const dialogElement = document.querySelector('.el-dialog');
        if (dialogElement) {
          console.log('对话框元素存在于DOM中');
          console.log('对话框样式：', window.getComputedStyle(dialogElement));
        } else {
          console.log('对话框元素不存在于DOM中');
        }
      });
    };

    // 对话框打开回调
    const onDialogOpen = () => {
      console.log('对话框已打开');

      // 检查对话框内容是否存在
      const dialogContent = document.querySelector('.el-dialog__content');
      if (dialogContent) {
        console.log('对话框内容存在');
      } else {
        console.log('对话框内容不存在');
      }
    };

    // 对话框关闭回调
    const onDialogClose = () => {
      console.log('对话框已关闭');
    };

    // 验证并保存课程
    const validateAndSave = () => {
      if (!formRef.value) return;

      formRef.value.validate((valid) => {
        if (valid) {
          handleSaveCourse();
        } else {
          console.error('表单验证失败');
          ElMessage.error('请填写所有必填字段');
          return false;
        }
      });
    };

    // 保存课程（新增/编辑）
    const handleSaveCourse = async () => {
      try {
        let res;

        if (isEditMode.value) {
          // 编辑课程
          res = await updateCourse({
            courseID: formData.value.courseID,
            name: formData.value.name,
            desc: formData.value.desc,
            Img: formData.value.img,
            price: formData.value.price
          });
        } else {
          // 新增课程
          res = await addCourse({
            name: formData.value.name,
            desc: formData.value.desc,
            Img: formData.value.img,
            price: formData.value.price
          });
        }

        if (res.code === 1) {
          dialogVisible.value = false;
          fetchCourseList();
          ElMessage.success(isEditMode.value ? '课程更新成功' : '课程新增成功');
        } else {
          console.error(isEditMode.value ? '课程更新失败' : '课程新增失败：', res.message);
          ElMessage.error(res.message || (isEditMode.value ? '课程更新失败' : '课程新增失败'));
        }
      } catch (error) {
        console.error('请求出错：', error);
        ElMessage.error('网络错误，请稍后重试');
      }
    };

    // 删除课程
    const handleDeleteCourse = (courseID) => {
      ElMessageBox.confirm(
          '确定要删除此课程吗？删除后将无法恢复。',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
      ).then(async () => {
        try {
          const res = await deleteCourse({ courseID });

          if (res.code === 1) {
            fetchCourseList();
            ElMessage.success('课程删除成功');
          } else {
            console.error('课程删除失败：', res.message);
            ElMessage.error(res.message || '课程删除失败');
          }
        } catch (error) {
          console.error('请求出错：', error);
          ElMessage.error('网络错误，请稍后重试');
        }
      }).catch(() => {
        // 取消操作
      });
    };

    // 分页相关方法
    const handleSizeChange = (newSize) => {
      pageSize.value = newSize;
      fetchCourseList();
    };

    const handleCurrentChange = (newPage) => {
      currentPage.value = newPage;
      fetchCourseList();
    };

    // 处理选中项变化
    const handleSelectionChange = (val) => {
      multipleSelection.value = val;
    };

    // 处理文件上传成功
    const handleUploadSuccess = (response, file) => {
      console.log('上传成功', response, file);

      const imageUrl = URL.createObjectURL(file.raw);
      formData.value.img = imageUrl;

      ElMessage.success('图片上传成功');
    };

    // 上传前处理
    const beforeUpload = (file) => {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG && !isPNG) {
        ElMessage.error('上传图片只能是 JPG 或 PNG 格式!');
        return false;
      }
      if (!isLt2M) {
        ElMessage.error('上传图片大小不能超过 2MB!');
        return false;
      }

      return true;
    };

    onMounted(() => {
      fetchCourseList();
    });

    return {
      courseList,
      currentPage,
      pageSize,
      total,
      dialogVisible,
      formData,
      dialogTitle,
      isEditMode,
      formRef,
      formRules,
      uploadUrl,
      uploadHeaders,
      fetchCourseList,
      openAddCourseDialog,
      openEditCourseDialog,
      onDialogOpen,
      onDialogClose,
      validateAndSave,
      handleSaveCourse,
      handleDeleteCourse,
      handleSizeChange,
      handleCurrentChange,
      handleSelectionChange,
      handleUploadSuccess,
      beforeUpload
    };
  }
};
</script>

<style scoped>
/* 样式保持不变 */
.course-management-page {
  padding: 20px;
  height: calc(100vh - 60px);
  display: flex;
  flex-direction: column;
}

.page-header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.course-list-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.course-table {
  margin-bottom: 20px;
}

.course-image {
  width: 80px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>